package com.ychen.ruijee.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ychen.ruijee.bean.Category;
import com.ychen.ruijee.bean.Dish;
import com.ychen.ruijee.bean.Setmeal;
import com.ychen.ruijee.dao.CategoryDao;
import com.ychen.ruijee.dao.DishDao;
import com.ychen.ruijee.dao.SetmealDao;
import com.ychen.ruijee.service.CategoryService;
import com.ychen.ruijee.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ychen@gotop.cn
 * @date 2024-05-31 0:34
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Resource
    private DishDao dishDao;

    @Resource
    private SetmealDao setmealDao;


    @Override
    public Page<Category> categoryPage(Integer page, Integer pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getSort);
        this.page(pageInfo);

        return pageInfo;
    }

    /**
     * 分类管理 判断当前分类总 是否关联了菜品
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteCategory(Long id) {
        // 1、判断当前 分类下 是否关联了菜品
        LambdaQueryWrapper<Dish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Dish::getCategoryId,id);
        Integer count1 = dishDao.selectCount(wrapper1);
        try {
            if (count1 >1 ){
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 判断当前放分类下是否关联了套餐
        LambdaQueryWrapper<Setmeal> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Setmeal::getCategoryId,id);
        Integer count2 = setmealDao.selectCount(wrapper2);
        try {
            if (count2 >1 ){
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 没有关联的时候 都删除
        boolean flag = this.removeById(id);


        return flag;
    }
}
